package com.zcc.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping({"/","/index","/index.html"})
    public String toIndex(Model model) {
        model.addAttribute("msg","Hello World");
        return "/index";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "/login";
    }

    @RequestMapping("/login")
    //参数是前端传递的用户登录信息
    public String login(String username, String password,Model model) {
        //获取用户
        Subject subject = SecurityUtils.getSubject();
        //执行登录，用令牌加密用户信息new UsernamePasswordToken()
        //异常捕获，提示用户名或者密码等问题
        try{
            subject.login(new UsernamePasswordToken(username, password));
            model.addAttribute("msg","Hello "+username+"!");
            subject.getSession().setAttribute("loginUser",username);
            return "/index";
        }catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg","账号或密码错误！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg","账户已锁定！");
            return "login";
        }
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "user/add";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate() {
        return "/user/update";
    }

    //权限不足页面
    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized() {
        return "没有访问该页面的权限";
    }
}
